package com.sharewin.shiro;

import com.sharewin.domain.Role;
import com.sharewin.domain.User;
import com.sharewin.service.PermissionService;
import com.sharewin.service.RoleService;
import com.sharewin.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author chenghai
 * @date 2021年07月17日 14:21
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 用户授权
     *
     * @param principals
     * @return org.apache.shiro.authz.AuthorizationInfo
     * @author chenghai
     * @date 2021/7/17 14:22
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        //获取用户角色
        List<Role> roleList = roleService.findRoleByUserId(user.getId());
        List<Integer> roleIds = roleList.stream().map(r -> r.getId()).collect(Collectors.toList());
        Set<String> roleSet = roleList.stream().map(r -> r.getRole()).collect(Collectors.toSet());
        //获取角色权限
        List<String> permissionList = permissionService.findByRoleId(roleIds);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roleSet);
        authorizationInfo.setStringPermissions(new HashSet<>(permissionList));
        return authorizationInfo;
    }

    /**
     * 用户认证
     *
     * @param token
     * @return org.apache.shiro.authc.AuthenticationInfo
     * @author chenghai
     * @date 2021/7/17 14:22
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        User user = userService.findByAccount(usernamePasswordToken.getUsername());
        if (user == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), user.getUsername());
    }
}
